package com.fsnbigdata.web;
import com.fsnbigdata.domain.Enterprise;
import com.fsnbigdata.enums.ResultEnum;
import com.fsnbigdata.exception.ParamException;
import com.fsnbigdata.util.ReflectUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.roo.addon.web.mvc.controller.annotations.ControllerType;
import org.springframework.roo.addon.web.mvc.controller.annotations.RooController;
import org.springframework.roo.addon.web.mvc.controller.annotations.responses.json.RooJSON;
import com.fsnbigdata.service.api.EnterpriseService;
import io.springlets.web.NotFoundException;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder;
import org.springframework.web.util.UriComponents;
import springfox.documentation.annotations.ApiIgnore;

import java.lang.reflect.Method;
import java.security.Principal;

/**
 * = EnterprisesItemJsonController
 *
 * TODO Auto-generated class documentation
 *
 */
@RooController(entity = Enterprise.class, pathPrefix = "/api", type = ControllerType.COLLECTION)
@RooJSON
@RestController
@RequestMapping(value = "/api/enterprises/{id}", name = "EnterprisesItemJsonController", produces = MediaType.APPLICATION_JSON_VALUE)
@Api(tags = "Enterprises", description = "生物企业及企业家信息数据库" )
public class EnterprisesItemJsonController {

    /**
     * TODO Auto-generated attribute documentation
     *
     */

    private EnterpriseService enterpriseService;

    /**
     * TODO Auto-generated constructor documentation
     *
     * @param enterpriseService
     */
    @Autowired
    public EnterprisesItemJsonController(EnterpriseService enterpriseService) {
        this.enterpriseService = enterpriseService;
    }

    /**
     * TODO Auto-generated method documentation
     *
     * @return EnterpriseService
     */
    public EnterpriseService getEnterpriseService() {
        return enterpriseService;
    }

    /**
     * TODO Auto-generated method documentation
     *
     * @param enterpriseService
     */
    public void setEnterpriseService(EnterpriseService enterpriseService) {
        this.enterpriseService = enterpriseService;
    }

    /**
     * TODO Auto-generated method documentation
     *
     * @param id
     * @return Enterprise
     */
    @ModelAttribute
    public Enterprise getEnterprise(@PathVariable("id") Long id) {
        Enterprise enterprise = enterpriseService.findOne(id);
        if (enterprise == null) {
            throw new NotFoundException(String.format("Enterprise with identifier '%s' not found", id));
        }
        return enterprise;
    }

    /**
     * TODO Auto-generated method documentation
     *
     * @param enterprise
     * @return ResponseEntity
     */
    @GetMapping(name = "show")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "", paramType = "path", dataType = "int", required = true)
    })
    public ResponseEntity<?> show(@ApiIgnore @ModelAttribute Enterprise enterprise) {
        return ResponseEntity.ok(enterprise);
    }

    /**
     * TODO Auto-generated method documentation
     *
     * @param enterprise
     * @return UriComponents
     */
    public static UriComponents showURI(Enterprise enterprise) {
        return MvcUriComponentsBuilder.fromMethodCall(MvcUriComponentsBuilder.on(EnterprisesItemJsonController.class).show(enterprise)).buildAndExpand(enterprise.getId()).encode();
    }

    /**
     * TODO Auto-generated method documentation
     *
     * @param storedEnterprise
     * @param enterprise
     * @param result
     * @return ResponseEntity
     */


    @PutMapping(name = "update")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "", paramType = "path", dataType = "int", required = true)
    })
    @PreAuthorize("hasRole('DB_ENTERPRISE')")
    @ApiOperation(value = "",notes = "update")
    public ResponseEntity<?> update(@ApiIgnore @ModelAttribute Enterprise storedEnterprise,
                                    @Valid @RequestBody Enterprise enterprise,
                                    BindingResult result) throws Exception {
        if (result.hasErrors()) {
            throw new ParamException(ResultEnum.PARAM_ERROR.getCode(),
                    result.getFieldError().getDefaultMessage());
        }

        enterprise.setId(storedEnterprise.getId());
        //删除原来的图片
        getEnterpriseService().deleteImages( enterprise.getId() );
        String name = getEnterpriseService().findByNameById( enterprise.getId());
        Enterprise newEnterprise = getEnterpriseService().save(enterprise);

        Class<?> clazz = EnterprisesItemJsonController.class;
        Method method = clazz.getMethod("update", ReflectUtil.getPeremeterClass(clazz, "update"));
        ReflectUtil.setAnnotationOn(method,"更新企业库，名称："+name);

        return ResponseEntity.ok(newEnterprise);
    }

    /**
     * TODO Auto-generated method documentation
     *
     * @param enterprise
     * @return ResponseEntity
     */
    @DeleteMapping(name = "delete")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "", paramType = "path", dataType = "int", required = true)
    })
    @PreAuthorize("hasRole('DB_ENTERPRISE')")
    @ApiOperation(value = "",notes = "delete")
    public ResponseEntity<?> delete(@ApiIgnore @ModelAttribute Enterprise enterprise) throws Exception {
        getEnterpriseService().delete(enterprise);
        Class<?> clazz = EnterprisesItemJsonController.class;
        Method method = clazz.getMethod("delete", ReflectUtil.getPeremeterClass(clazz, "delete"));
        ReflectUtil.setAnnotationOn(method,"删除企业库，名称："+enterprise.getName());
        return ResponseEntity.ok().build();
    }
}
